<?php

namespace App\Http\Controllers\Home;

//引入微博设置文件和核心类文件
require_once(base_path('/config/apiconfig.php'));
require_once(app_path('/Tool/API/WB/SaetvtExClass.php'));

use App\Models\Home\User;
use App\Models\Home\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;

class OauthController extends Controller
{
    //微博登录
    //请求授权获取code
    public function wbLogin(){
        $o = new \SaeTOAuthV2(WB_KEY, WB_SEC);
        $url = url('/oauth/weibo/callback');
        $oauth = $o->getAuthorizeURL($url);
        //跳转到登录授权页面
        return redirect($oauth);
    }
    //回调获取code请求token
    public function wbCallBack()
    {
        $o = new \SaeTOAuthV2(WB_KEY, WB_SEC);

        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = WB_CALLBACK_URL;
            try {
                $token = $o->getAccessToken('code', $keys);
            } catch (\OAuthException $e) {
            }
        }

        if ($token) {
            //将token存入session, 命名为wbtoken
            //Session::put('wbtoken', $token);
            //在user表中确认token是否存在
            $res = User::where('id', $token['uid'])->first();
            if(!$res){
            //如果不存在该uid, 将该用户注册到用户列表
            $user = new User();
            $user->id = $token['uid'];
            $user->created_at = getTimeFormat();
            $user->save();
            Session::put('user.id', $token['uid']);
            $users = new UserInfo();
            $users->user_id = $token['uid'];
            $users->nickname = randomNickname();
            $users->address = '0,0,0';
            $users->avatar = '/images/80x80.png';
            $users->bgd = '/images/background/04.jpeg';
            $users->save();
            Session::put('user.nickname', $users->nickname);
            Session::put('user.avatar', $users->avatar);
            Session::put('user.bgd', $users->bgd);
            Session::save();
            return redirect(url('/'));
            }else{
                //如果存在，则将信息取出存进session
                $uid = UserInfo::where('user_id', $token['uid'])->first();
                Session::put('user.id', $token['uid']);
                Session::put('user.nickname', $uid->nickname);
                Session::put('user.avatar', $uid->avatar);
                Session::put('user.bgd', $uid->bgd);
                Session::save();
                return redirect(url('/'));
            }
        } else {
            echo '授权失败。';
            return redirect(url('/login'));
        }
    }
}
